import pymysql


class DBUtil:
    # 全局变量
    conn = None

    # 建立连接
    @classmethod
    def __getconnect(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2025", database="ihrm", charset="utf8")

        return cls.conn

    # 关闭连接
    @classmethod
    def __closeconnect(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn = None

    # 查询方法
    @classmethod
    def selectone_db(cls, sql):
        cursor = None
        try:
            # 获取连接
            cls.conn = cls.__getconnect()
            # 获取游标
            cursor = cls.conn.cursor()
            # 游标执行
            cursor.execute(sql)
            # 结果集中取一个
            res = cursor.fetchone()
            return res
        except Exception as e:
            print("查询sql错误", str(e))
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__closeconnect()

    # 增删改方法
    @classmethod
    def idu_db(cls, sql):
        cursor = None
        try:
            # 获取连接
            cls.conn = cls.__getconnect()
            # 获取游标
            cursor = cls.conn.cursor()
            # 游标执行
            cursor.execute(sql)
            print("影响行数：", cls.conn.affected_rows())
            # 事务提交
            cls.conn.commit()
        except Exception as e:
            print("增删改sql错误", str(e))
            # 事务回滚
            cls.conn.rollback()
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__closeconnect()


if __name__ == '__main__':
    res=DBUtil.selectone_db("select * from bs_user")
    print(res)